package com.uxsino.simo.indicator.retractor;

import com.google.common.base.Strings;
import org.apache.commons.lang3.StringUtils;

import com.uxsino.commons.utils.config.ConfigProp;
import com.uxsino.commons.utils.config.PropElement;
import com.uxsino.reactorq.model.INDICATOR_TYPE;
import com.uxsino.simo.indicator.Indicator;
import com.uxsino.simo.networkentity.EntityInfo;
import com.uxsino.simo.query.QueryContext;
import com.uxsino.simo.query.QueryTemplate;
import com.uxsino.simo.utils.ConfigLoadingContext;

public class SimpleValueRetractor extends AbstractValueRetractor<Object> {

    @ConfigProp(name = "map")
    public void setMap(String expr) {
        valueMap = new ValueMap();
        valueMap.addFromStringList(expr);
    }

    @ConfigProp(name = "trim")
    public boolean trimResultString = true;

    private ValueMap valueMap;

//    private StringExprTransformer transformer;
//
//    @ConfigProp(name = "transform")
//    public void setTransformer(String expr) {
//        if (expr != null)
//            transformer = new StringExprTransformer(expr);
//        else
//            transformer = null;
//    }

    public SimpleValueRetractor(INDICATOR_TYPE valueType) {
        super(valueType);
    }

    public Object convertValue(Object o) throws NumberFormatException {

        switch (valueType) {
        case STRING:
            if (StringUtils.isBlank(o.toString())) {
                return null;
            }
            if (trimResultString) {
                o = o.toString().trim();
            }
            if (valueMap != null) {
                String r = valueMap.get(o.toString());
                if (r != null)
                    o = r;
            }
            break;
        case NUMBER:
            try {
                o = Double.parseDouble(o.toString());
            } catch (Exception e) {
                return null;
            }
            break;
        case BOOLEAN:
            try {
                o = Boolean.valueOf(o.toString());
            }catch (Exception e){
                return null;
            }
        default:
            break;
        }

        /*if (!Strings.isNullOrEmpty(transformer)) {
            o = transForm(o);
        }*/
        return o;
    }

    @Override
    public Object doRetract(EntityInfo entity, QueryContext ctxt, QueryTemplate qt, Object obj) {

        return obj == null ? null : convertValue(obj.toString());
    }

    @Override
    public void loadProp(Indicator ind, PropElement eRetractor, ConfigLoadingContext lctxt) {

    }

    @Override
    public void addFieldExpr(String fieldName, EXPRTYPE exprType, String expr) {

    }

    @Override
    public void postRetract(EntityInfo entity, QueryContext ctxt, QueryTemplate qt, Object obj) {

    }

}
